package com.terren.statistic.execute;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.terren.statistic.common.entity.Documents;
import com.terren.statistic.common.entity.SysConfig;
import com.terren.statistic.common.util.CommonUtil;
import com.terren.statistic.common.util.HttpClient;
import com.terren.statistic.common.util.LogUtil;
import com.terren.statistic.execute.excel.DocExport2Excel;

public class BasicStatistic {
	
	private static Logger logger = LogUtil.getLogger(BasicStatistic.class);
	
	protected ArrayList<Documents> docList;
	protected static final short OFFICIAL_SITE = 0;//官媒
	protected static final short PORTAL_SITE = 1;//门户
	protected String fileFormat;
	protected static String path;
	
	public BasicStatistic() {
		this.fileFormat = SysConfig.FILE_FORMAT;
	}

	protected void exportExcel(int cType, String startTime, String endTime, String keyword) {
		String fileName = "_" + cType + "_" + startTime.replaceAll("\\-", "") + "_" + endTime.replaceAll("\\-", "");
		try {
			DocExport2Excel dee = new DocExport2Excel();
			dee.createExcel(docList, fileName, path);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void exportJson(int cType, String startTime, String endTime, String keyword) throws Exception {
		String result = "";
		String fileName = path + File.separator +"file" + cType + "_" + startTime.replaceAll("\\-", "") + "_" + endTime.replaceAll("\\-", "")
				+ ".json";
		File htmlFile = new File(fileName);
		OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8");
		BufferedWriter bw = new BufferedWriter(fw);
		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
			result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(docList);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		bw.append(result);
		bw.close();
		fw.close();
	}

	protected void exportHtml(int cType, String startTime, String endTime, String keyword) throws Exception {
		String fileName = path + File.separator +"file" + cType + "_" + startTime.replaceAll("\\-", "") + "_" + endTime.replaceAll("\\-", "") + ".html";
		File htmlFile = new File(fileName);
		// 用OutputStreamWriter 替代 FileWriter，解决写UTF8格式文件的问题
		// FileWriter fw = new FileWriter(nodesFile);
		OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8");
		BufferedWriter bw = new BufferedWriter(fw);
		bw.append("<!DOCTYPE HTML>");
		bw.append("<html>");
		bw.append("<head>");
		bw.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
		bw.append("<title>" + keyword + "相关新闻</title>");
		bw.append("</head>");
		bw.append("<body>");
		for (Documents doc : docList) {
			bw.append("<div>");
			String title = "<a href=\"[URL]\"><h1>[TITLE]</h1></a>";
			bw.append(title.replace("[URL]", doc.getUrl()).replace("[TITLE]", doc.getTitle()));
			String pubTimeSource = "<div><span>[PUBTIME]</span><span>[SOURCE]</span></div>";
			bw.append(pubTimeSource.replace("[PUBTIME]", doc.getPublishDay()).replace("[SOURCE]", doc.getCustomer()));
			String pvUv;
			if (cType == 0)
				pvUv = "<div><span>浏览量：[PV]&nbsp;&nbsp;</span><span>访客数：[UV]</span></div>";
			else if (cType == 1)
				pvUv = "<div><span>参与数：[PV]&nbsp;&nbsp;</span><span>评论数：[UV]</span></div>";
			else if (cType == 8)
				pvUv = "<div><span>阅读数：[PV]&nbsp;&nbsp;</span><span>点赞数：[UV]</span></div>";
			else
				pvUv = "<div><span></span><span></span></div>";
			bw.append(pvUv.replace("[PV]", "" + doc.getPv()).replace("[UV]", "" + doc.getUv()));
			bw.append("<p>");
			bw.append(doc.getContent());
			bw.append("</p>");
			bw.append("</div>");
			bw.append("</br>");
		}
		bw.append("</body>");
		bw.close();
		fw.close();
	}

	protected boolean mkdir(File filePath) {
		// 判断目标文件所在的目录是否存在
		if (!filePath.getParentFile().exists()) {
			// 如果目标文件所在的目录不存在，则创建父目录
			if (!filePath.getParentFile().mkdirs()) {
				logger.error("mkdir " + filePath + " failed!");
				return false;
			}
		}
		return true;
	}

	protected void exportTxt(int cType, String startTime, String endTime, String keyword) throws Exception {
		for (Documents doc : docList) {
			String exportPath = path + File.separator + cType + "/" + startTime.substring(0, 7);
			String fileName = exportPath + "/" + CommonUtil.getSingleId() + ".txt";
			File txtFile = new File(fileName);
			if (mkdir(txtFile)) {
				// 用OutputStreamWriter 替代 FileWriter，解决写UTF8格式文件的问题
				// FileWriter fw = new FileWriter(nodesFile);
				OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(txtFile), "UTF-8");
				BufferedWriter bw = new BufferedWriter(fw);
				bw.append("关键词：");
				bw.append(keyword);
				bw.append(System.lineSeparator());
				bw.append("内容格式：");
				if (cType == 0)
					bw.append("标题 ||| 链接 ||| 发布时间 ||| 来源 ||| 浏览量 ||| 访客数 ||| 正文内容");
				else if (cType == 1)
					bw.append("标题 ||| 链接 ||| 发布时间 ||| 来源 ||| 参与数 ||| 评论数 ||| 正文内容");
				else if (cType == 8)
					bw.append("标题 ||| 链接 ||| 发布时间 ||| 来源 ||| 阅读数 ||| 点赞数 ||| 正文内容");
				else
					bw.append("标题 ||| 链接 ||| 发布时间 ||| 来源 ||| - ||| - ||| 正文内容");

				bw.append(System.lineSeparator());
				String format = "[TITLE]|||[URL]|||[PUBTIME]|||[SOURCE]|||[PV]|||[UV]|||[CONTENT]";
				String text = format.replace("[TITLE]", doc.getTitle()).replace("[URL]", doc.getUrl())
						.replace("[PUBTIME]", doc.getPublishDay()).replace("[SOURCE]", doc.getCustomer())
						.replace("[PV]", "" + doc.getPv()).replace("[UV]", "" + doc.getUv())
						.replace("[CONTENT]", doc.getContent() == null ? "" : doc.getContent());
				bw.append(text);
				bw.close();
				fw.close();
			}
		}
	}
	
	protected String getDataByUrl(String url, String cTypeStr, String kw, String st, String et, int offset) throws Exception {
		kw = kw.replaceAll("（", "(").replaceAll("）", ")").replaceAll("＆", "&").replaceAll("｜", "|")
				.replaceAll("&\\|", "&").replaceAll("\\|&", "|").replaceAll("\\(\\|", "(").replaceAll("\\(&", "(")
				.replaceAll("\\|\\)", ")").replaceAll("&\\)", ")");
		url = url.replace("[RIDXHOST]", SysConfig.RIDX_HOST).replace("[RIDXPORT]", String.valueOf(SysConfig.RIDX_PORT))
				.replace("[KW]", URLEncoder.encode(kw, "UTF8")).replace("[CTYPE]", cTypeStr).replace("[PS]", st)
				.replace("[PE]", et);
		url += "&limit="+ SysConfig.LIMIT +"&offset=" + offset;
		logger.info(url);
		HttpClient hc = new HttpClient(SysConfig.RIDX_HOST, SysConfig.RIDX_PORT);
		hc.setTimeout((short) 180);
		return hc.pageReader("GET", url, "");
	}
	
}
